|
1
|
|
|
'use strict'; |
|
2
|
|
|
|
|
3
|
|
|
/* Magic Mirror |
|
4
|
|
|
* Module: MMM-Smappee |
|
5
|
|
|
* |
|
6
|
|
|
* By Christopher Fenner http://github.com/CFenner |
|
7
|
|
|
* MIT Licensed. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
const NodeHelper = require('node_helper'); |
|
11
|
|
|
const oauth2 = require('simple-oauth2'); |
|
12
|
|
|
const request = require('request-promise'); |
|
13
|
|
|
const HOST = 'https://app1pub.smappee.net'; |
|
14
|
|
|
const ENDPOINT = '/dev/v1'; |
|
15
|
|
|
const AUTH_PATH = '/oauth2/token'; |
|
16
|
|
|
const SERVICE_PATH = '/servicelocation'; |
|
17
|
|
|
//const CONSUMPTION_PATH = '/{serviceId}/consumption'; |
|
18
|
|
|
|
|
19
|
|
|
module.exports = NodeHelper.create({ |
|
20
|
|
|
start: function () { |
|
21
|
|
|
console.log("Starting node helper for " + this.name); |
|
|
|
|
|
|
22
|
|
|
}, |
|
23
|
|
|
getLocations: function(token){ |
|
24
|
|
|
this.accessToken = this.auth.accessToken.create(token); |
|
25
|
|
|
return request.get( |
|
26
|
|
|
HOST + ENDPOINT + SERVICE_PATH, { |
|
27
|
|
|
'auth': {'bearer': this.accessToken.token.access_token}, |
|
28
|
|
|
json: true |
|
29
|
|
|
}); |
|
30
|
|
|
}, |
|
31
|
|
|
getConsumption: function(locations){ |
|
32
|
|
|
var location = locations.serviceLocations[0].serviceLocationId; |
|
33
|
|
|
var to = new Date().getTime(); |
|
34
|
|
|
return request.get( |
|
35
|
|
|
HOST + ENDPOINT + SERVICE_PATH + '/' + location + '/consumption', { |
|
36
|
|
|
'auth': {'bearer': this.accessToken.token.access_token}, |
|
37
|
|
|
json: true, |
|
38
|
|
|
qs: { |
|
39
|
|
|
aggregation: 1, |
|
40
|
|
|
from: to - 900000, |
|
41
|
|
|
to: to, |
|
42
|
|
|
} |
|
43
|
|
|
}); |
|
44
|
|
|
}, |
|
45
|
|
|
socketNotificationReceived: function(notification, payload) { |
|
46
|
|
|
if('SMAPPEE_LOAD' === notification){ |
|
47
|
|
|
var self = this; |
|
48
|
|
|
if(!self.auth){ |
|
49
|
|
|
self.auth = oauth2.create({ |
|
50
|
|
|
client: { |
|
51
|
|
|
id: payload.client.id, |
|
52
|
|
|
secret: payload.client.secret |
|
53
|
|
|
}, |
|
54
|
|
|
auth: { |
|
55
|
|
|
tokenHost: HOST, |
|
56
|
|
|
tokenPath: ENDPOINT + AUTH_PATH |
|
57
|
|
|
} |
|
58
|
|
|
}); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
self.auth.ownerPassword.getToken({ |
|
62
|
|
|
username: payload.user.id, |
|
63
|
|
|
password: payload.user.password |
|
64
|
|
|
}).then( |
|
65
|
|
|
self.getLocations.bind(self) |
|
66
|
|
|
).then( |
|
67
|
|
|
self.getConsumption.bind(self) |
|
68
|
|
|
).then((response) => { |
|
69
|
|
|
self.sendSocketNotification('SMAPPEE_DATA', response.consumptions.pop()); |
|
70
|
|
|
}).catch(console.log); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
}); |
|
74
|
|
|
|